package com.pangolin.pangolinim.ui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jaeger.library.StatusBarUtil;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.app.mainApp;
import com.pangolin.pangolinim.net.NetFormat;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.base.BaseActivity;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.SPUtil;
import com.pangolin.pangolinim.utils.UIUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SplashActivity extends BaseActivity {
    private RelativeLayout mRlButton;
    private Button mBtnLogin;
    private Button mBtnRegister;

    private int mUid;          //临时存放缓存中的用户uid
    private String mPasswd;     //临时存放缓存中的用户密码

    @Override
    protected void init(){
        //申请权限（摄像头、外置存储读写）
        checkPermissions();

        //检查外部存储卡状态
        checkExternalStorage();

        //获取缓存的用户uid和密码
        mUid = (int) SPUtil.get(this , "uid" , 0);
        mPasswd = (String) SPUtil.get(this , "passwd" , "");
        Logger.d("getSharedPreferences : %d|%s" , mUid , mPasswd);

        //清理其他activity。主要为了切换账号登陆时能清理环境
        closeOtherActivity();
    }

    @Override
    protected void initView(){
        mRlButton = findViewById(R.id.rlButton);
        mBtnRegister = findViewById(R.id.btnRegister);
        mBtnLogin = findViewById(R.id.btnLogin);

        StatusBarUtil.setColor(this, UIUtil.getColor(R.color.black));

        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(1000);
        mRlButton.startAnimation(alphaAnimation);
    }

    @Override
    protected void initListener(){
        mBtnLogin.setOnClickListener(v -> {
            jumpToActivity(LoginActivity.class);
            finish();
        });
        mBtnRegister.setOnClickListener(v -> {
            jumpToActivity(RegisterActivity.class);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCoreService();
    }

    @Override
    protected void CoreMessage(BundleUtil bundleUtil){
        Logger.d("CoreMessage:%d" , bundleUtil.getType());
        if(bundleUtil.getType() == BroadcastMsg.SIG_CORE_SERVSTARED) {
            /** 根据缓存的用户uid和密码尝试登陆 */
            if(mUid > 0 && mPasswd.length() > 0){
                login(mUid , mPasswd);
            }
        }else if(bundleUtil.getType() == BroadcastMsg.SIG_CORE_DATA){
            if(bundleUtil.getData() != null){
                Map<String, Object> resMap = bundleUtil.getData();
                Logger.d(resMap);
                if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_LOGIN){       //登陆请求返回
                    if((int)resMap.get("result") == 0){
                        UIUtil.showToast("登陆成功");
                        UIContact me = new UIContact();
                        me.setUid(mUid);
                        me.setName((String) resMap.get("name"));
                        me.setHeader((String) resMap.get("headimg"));
                        jumpToActivity(MainActivity.class , GsonUtil.toJson(me));
                        finish();
                    }else{
                        UIUtil.showToast(NetFormat.ResMsg((int) resMap.get("result")));
                        if((int) resMap.get("result") == 3){
                            //登陆失败则清除缓存用户密码
                            SPUtil.remove(this , "uid");
                            SPUtil.remove(this , "passwd");
                        }
                    }
                }
            }
        }
    }

    @Override
    protected int provideContentViewId(){
        return R.layout.activity_splash;
    }

    private void checkPermissions(){
        if (ContextCompat.checkSelfPermission(mainApp.getContext(),Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(mainApp.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(mainApp.getContext(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
            List<String> permissionsNeeded = new ArrayList<String>();
            permissionsNeeded.add(Manifest.permission.CAMERA);      //摄像头
            permissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);   //读取外置存储卡
            permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);  //写入外置存储卡
            String[] permissions = permissionsNeeded.toArray(new String[permissionsNeeded.size()]);
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
    }

    private boolean checkExternalStorage(){
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            UIUtil.showToast("找不到外置存储，程序无法正常运行");
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode , permissions , grantResults);
        if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            UIUtil.showToast("拒绝授权可能导致程序无法正常运行");
        }else{
            //通知后台启动服务
            startCoreService();
        }
    }

    private void login(int uid , String passwd){
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_LOGIN);
        brocastMap.put("uid" , uid);
        brocastMap.put("passwd" , passwd);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtil.getBundle());
    }
}